﻿using ComponentFactory.LcrMes.Toolkit.QControls;
using ComponentFactory.LcrMes.Toolkit;
using NPOI.OpenXmlFormats.Dml.Chart;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using static NPOI.HSSF.Util.HSSFColor;
using System.Web.UI;
using Control = System.Windows.Forms.Control;
using System.Net.Sockets;
using System.Net;
using System.Management;

namespace GKQC.Common
{
    /// <summary>
    /// 窗體處理類
    /// </summary>
    public class FormCommon
    {
        static Color SelectedBackgroupColor = Color.FromArgb(18, 150, 219);//RGB(18,150,219)
        static Brush brush = new SolidBrush(SelectedBackgroupColor);

        /// <summary>
        /// 向下递归查找控件
        /// </summary>
        /// <param name="parentControl">查找控件的父容器控件</param>
        /// <param name="findCtrlName">查找控件名称</param>
        /// <returns>若没有查找到返回NULL</returns>
        public static Control FindControl(Control parentControl, string findCtrlName)
        {
            Control _findedControl = null;
            if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
            {
                foreach (Control ctrl in parentControl.Controls)
                {
                    if (ctrl.Name.Equals(findCtrlName))
                    {
                        _findedControl = ctrl;
                        break;
                    }
                    else
                    {
                        if(ctrl is SplitContainer)
                        {
                            SplitContainer s = ctrl as SplitContainer;
                            _findedControl = FindControl(s.Panel1, findCtrlName);
                            if(_findedControl == null)
                                _findedControl = FindControl(s.Panel2, findCtrlName);
                        }
                        if (ctrl.Controls.Count > 0)
                            _findedControl = FindControl(ctrl, findCtrlName);

                    }
                }
            }
            return _findedControl;
        }
        /// <summary>
        /// 将Control转换某种控件类型
        /// </summary>
        /// <typeparam name="T">控件类型</typeparam>
        /// <param name="control">Control</param>
        /// <param name="result">转换结果</param>
        /// <returns>若成功则返回控件；若失败则返回NULL</returns>
        public static T Cast<T>(Control control, out bool result) where T : Control
        {
            result = false;
            T _castCtrl = null;
            if (control != null)
            {
                if (control is T)
                {
                    try
                    {
                        _castCtrl = control as T;
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(ex);
                        result = false;
                    }
                }
            }
            return _castCtrl;
        }

        /// <summary>
        /// 判断输入数字是否合理
        /// </summary>
        /// <param name="tb"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static bool CheckDigitFormat(TextBox tb, KeyPressEventArgs e)
        {
            bool flag = false;
            if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != 46)
            {
                flag = true;

            }
            // 小数点的处理
            if (e.KeyChar == 46)
            {
                if (tb.Text.Length <= 0)
                    flag = true;   //小数点不能在第一位
                else
                {
                    // 判断是否是正确的小数格式
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(tb.Text, out oldf);
                    b2 = float.TryParse(tb.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            flag = true;
                        else
                            flag = false;
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 計算到期日期
        /// </summary>
        /// <param name="testDate">試驗日期</param>
        /// <param name="testTime">試驗時間</param>
        /// <returns></returns>
        public static DateTime GetExpireDate(DateTime testDate, decimal testTime)
        {
            DateTime expireDate = testDate;
            if (testTime <= 0) ;
            else if (testTime == 125)
                expireDate = expireDate.AddDays(6);
            else if (testTime == 168)
                expireDate = expireDate.AddDays(7);
            else if (testTime == 250)
                expireDate = expireDate.AddDays(12);
            else if (testTime == 500)
                expireDate = expireDate.AddDays(22);
            else if (testTime == 750)
                expireDate = expireDate.AddDays(33);
            else if (testTime == 1000)
                expireDate = expireDate.AddDays(44);
            else if (testTime == 2000)
                expireDate = expireDate.AddDays(88);
            else
                expireDate = expireDate.AddDays(Convert.ToDouble(Math.Ceiling(testTime / 24m)));

            return expireDate;
        }

        /// <summary>
        /// 值为0的时候全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void TextBox_GotFocus(object sender, EventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox == null) return;
            if(textBox.Text == "0")
            {
                textBox.SelectAll();
            }
        }

        /// <summary>
        /// 值为0的时候全选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void TextBox_MouseUp(object sender, MouseEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox == null) return;
            if (textBox.Text == "0")
            {
                textBox.SelectAll();
            }
        }

        static string _string = "string";
        static string zero = "0";
        /// <summary>
        /// 值为0的时候不显示
        /// </summary>
        /// <param name="head">TextBox绑定的控件</param>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void TextBoxNoDisplayZero_TextChanged(object head,object sender, EventArgs e)
        {
            try
            {
                if (head == null) return;
                TextBox txt = sender as TextBox;
                if (txt == null) return;

                if (txt.Text == zero) txt.Text = string.Empty;
                if (string.IsNullOrWhiteSpace(txt.Text))
                {
                    string propertyName = string.Empty;
                    if(txt.DataBindings.Count > 0)
                    {
                        propertyName = txt.DataBindings[0].BindingMemberInfo.BindingMember;
                    }
                    if (string.IsNullOrWhiteSpace(propertyName)) return;
                    var p = head.GetType().GetProperty(propertyName);
                    if (p == null) return;
                    if (p.PropertyType.Name == _string)
                        p.SetValue(head, zero, null);
                    else
                        p.SetValue(head, 0, null);
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        /// <summary>
        /// 綁定來源單據類型Dictionnary到ComboBox
        /// </summary>
        /// <param name="comboBox"></param>
        public static void SetSourceCode(ComboBox comboBox)
        {
            try
            {
                Dictionary<string, string> freqs = new Dictionary<string, string>();
                freqs.Add("D512", "D512");
                freqs.Add("B520", "B520");
                freqs.Add("T341", "T341");
                BindingSource bs = new BindingSource();
                bs.DataSource = freqs;

                comboBox.DisplayMember = "Key";
                comboBox.ValueMember = "Value";
                comboBox.DataSource = bs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "異常S0037", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 初始化等級下拉框
        /// </summary>
        public static void SetLevel(ComboBox cboLevel)
        {
            try
            {
                Dictionary<string, string> levels = new Dictionary<string, string>();
                levels.Add("A", "A");
                levels.Add("B", "B");
                levels.Add("C", "C");
                BindingSource bs = new BindingSource();
                bs.DataSource = levels;

                cboLevel.DisplayMember = "Key";
                cboLevel.ValueMember = "Value";
                cboLevel.DataSource = bs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "異常S0039", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static void SetTestTarget(ComboBox cboTestTarget)
        {
            try
            {
                Dictionary<string, string> levels = new Dictionary<string, string>();
                levels.Add("For Approval", "For Approval");
                levels.Add("In-material test", "In-material test");
                levels.Add("Regular test", "Regular test");
                levels.Add("For Research", "For Research");
                levels.Add("study test", "study test");
                levels.Add("quantity production test", "quantity production test");
                levels.Add("customer request", "customer request");
                levels.Add("new material test", "new material test");
                levels.Add("material comparison test", "material comparison test");

                BindingSource bs = new BindingSource();
                bs.DataSource = levels;

                cboTestTarget.DisplayMember = "Key";
                cboTestTarget.ValueMember = "Value";
                cboTestTarget.DataSource = bs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "異常S0040", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static void SetRippleCurrentFreq(ComboBox combobBox)
        {
            try
            {
                DataTable dt = new DataTable("RippleCurrent");
                dt.Columns.Add(new DataColumn("Value", typeof(string)));
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                //纹波电流分写法:100mA(120Hz)或者100mA(100Khz)
                DataRow r = dt.NewRow();
                r["Value"] = "120Hz";
                r["Name"] = r["Value"];
                dt.Rows.Add(r);
                r = dt.NewRow();
                r["Value"] = "100Khz";
                r["Name"] = r["Value"];
                dt.Rows.Add(r);

                combobBox.DisplayMember = "Value";
                combobBox.ValueMember = "Name";
                combobBox.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "異常S0059", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
        public static void SetLType(ComboBox combobBox)
        {
            try
            {
                DataTable dt = new DataTable("LType");
                dt.Columns.Add(new DataColumn("Value", typeof(string)));
                dt.Columns.Add(new DataColumn("Name", typeof(string)));
                //纹波电流分写法:100mA(120Hz)或者100mA(100Khz)
                DataRow r = dt.NewRow();
                r["Value"] = "L";
                r["Name"] = r["Value"];
                dt.Rows.Add(r);
                r = dt.NewRow();
                r["Value"] = "L'";
                r["Name"] = r["Value"];
                dt.Rows.Add(r);

                combobBox.DisplayMember = "Value";
                combobBox.ValueMember = "Name";
                combobBox.DataSource = dt;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "異常S0704", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static string GetDataTableComboBoxValue(ComboBox cbo)
        {
            string item = string.Empty;
            try
            {
                if (cbo.SelectedItem != null)
                {
                    DataRowView v = cbo.SelectedItem as DataRowView;
                    if (v != null)
                    {
                        item = v["value"].ToString();
                    }
                }
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
            }
            return item;
        }

        public static string GetDataTableComboBoxName(ComboBox cbo)
        {
            string item = string.Empty;
            try
            {
                if (cbo.SelectedItem != null)
                {
                    DataRowView v = cbo.SelectedItem as DataRowView;
                    if (v != null)
                    {
                        item = v["Name"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            return item;
        }

        public static List<Control> GetAllSubControls(Control parentControl)
        {
            List<Control> list = new List<Control>();

            foreach(Control c in parentControl.Controls)
            {
                list.Add(c);
                if (c.Controls != null && c.Controls.Count >0)
                {
                    list.AddRange(GetAllSubControls(c));
                }
            }

            return list;
        }

        /// <summary>
        /// 数值类控件不显示0处理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="root"></param>
        /// <param name="txtD_TextChanged">不显示0，在里面</param>
        public static void NumberControlZeroDeal<T>(Control root, EventHandler txtD_TextChanged)
        {
            try
            {
                Type type = typeof(T);
                object obj = Activator.CreateInstance(type);
                var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                var controls = FormCommon.GetAllSubControls(root);
                if (controls != null && controls.Count > 0)
                {
                    foreach (Control c in controls)
                    {
                        if (c.DataBindings.Count == 0) continue;
                        if (c.GetType() == typeof(TextBox))
                        {
                            TextBox t = c as TextBox;
                            var pro = type.GetProperty(c.DataBindings[0].BindingMemberInfo.BindingField);
                            if (pro == null) continue;
                            if (pro.PropertyType == typeof(int)
                                || pro.PropertyType == typeof(double)
                                || pro.PropertyType == typeof(decimal)
                                || pro.PropertyType == typeof(float)
                                )
                            {
                                t.GotFocus += new EventHandler(TextBox_GotFocus);
                                t.MouseUp += new MouseEventHandler(TextBox_MouseUp);
                                t.TextChanged += new EventHandler(txtD_TextChanged);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }


        static string ND = "ND";
        static string _0 = "0";
        /// <summary>
        /// Rohs控件0值显示ND处理
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="root"></param>
        /// <param name="txtD_TextChanged">不显示0，在里面</param>
        public static void TextBoxRohsND(Control root)
        {
            try
            {
                var controls = FormCommon.GetAllSubControls(root);
                if (controls != null && controls.Count > 0)
                {
                    foreach (Control c in controls)
                    {
                        if (c.GetType() == typeof(TextBox))
                        {
                            TextBox t = c as TextBox;
                            t.TextChanged += new EventHandler(T_TextChanged);
                            t.MouseUp += new MouseEventHandler(TextBox_MouseUp);
                            t.GotFocus += new EventHandler(TextBox_GotFocus);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }


        private static void T_TextChanged(object sender, EventArgs e)
        {
            try
            {
                TextBox t = sender as TextBox;
                if (t.Text == _0)
                    t.Text = ND;
            }
            catch(Exception ex)
            {

            }
        }

        public static void TabControl_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
        {
            try
            {
                TabControl tabControl1 = sender as TabControl;
                if (tabControl1 == null) return;
                StringFormat sf = new StringFormat();
                sf.LineAlignment = StringAlignment.Center;
                sf.Alignment = StringAlignment.Center;
                e.Graphics.FillRectangle(Brushes.AliceBlue, e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);
                Color color = e.Index == tabControl1.SelectedIndex ? SelectedBackgroupColor : Color.Black;
                e.Graphics.DrawString(((TabControl)sender).TabPages[e.Index].Text,
                System.Windows.Forms.SystemInformation.MenuFont, new SolidBrush(color), e.Bounds, sf);
            }
            catch { }
        }

        public static void SetControlEnable(Control control, bool isEdit)
        {
            if (control.GetType().Name == typeof(Label).Name) return;
            if (control.GetType().Name == typeof(TextBox).Name)
            {
                ((TextBox)control).ReadOnly = !isEdit;
            }
            else if (control.GetType().Name == typeof(QTextBox).Name)
            {
                var c = ((QTextBox)control);
                c.ReadOnly = !isEdit;
            }
            else if (control.GetType().Name == typeof(ComboBox).Name || control.GetType().Name == typeof(QComboBox).Name)
            {
                
                if (control is QComboBox)
                {
                    var c = ((QComboBox)control);
                    c.Enabled = isEdit;
                    if (c.EnableAlways)
                        c.Enabled = false;
                }
            }
            else if (control.GetType().Name == typeof(CheckBox).Name || control.GetType().Name == typeof(QCheckBox).Name)
            {
                if (control is QCheckBox)
                {
                    var c = ((QCheckBox)control);
                    c.Enabled = isEdit;
                    if (c.EnableAlways)
                        c.Enabled = false;
                }
            }
            else if (control.GetType().Name == typeof(NumericUpDown).Name)
            {
                ((NumericUpDown)control).Enabled = isEdit;
            }
            else if (control.GetType().Name == typeof(QNumericUpDown).Name)
            {
                var c = ((QNumericUpDown)control);
                c.Enabled = isEdit;
                if (c.EnableAlways)
                    c.Enabled = false;
            }
            else if (control.GetType().Name == typeof(DateTimePicker).Name)
            {
                var c = ((DateTimePicker)control);
                c.Enabled = true;
            }
            else if (control.GetType().Name == typeof(QDateTimePicker).Name)
            {
                var c = ((QDateTimePicker)control);
                c.Enabled = true;

                if (c.EnableAlways)
                    c.Enabled = false;
            }
            else if (control.GetType().Name == typeof(LcrMesTextBox).Name)
            {
                var c = ((LcrMesTextBox)control);
                c.ReadOnly = !isEdit;
                if (c.EnableAlways)
                    c.ReadOnly = false;
            }
            else if (control.GetType().Name == typeof(LcrMesComboBox).Name)
            {
                control.Enabled = isEdit;

                var c = ((LcrMesComboBox)control);
                if (c.EnableAlways)
                    c.Enabled = false;
            }
            else if (control.GetType().Name == typeof(LcrMesNumericUpDown).Name)
            {
                var c = ((LcrMesNumericUpDown)control);
                c.Enabled = isEdit;
                if (c.EnableAlways)
                    c.Enabled = false;
            }
            else if (control.GetType().Name == typeof(LcrMesDateTimePicker).Name)
            {
                var c = ((LcrMesDateTimePicker)control);
                c.Enabled = isEdit;
                if (c.EnableAlways)
                    c.Enabled = true;
            }
            else if (control.GetType().Name == typeof(LcrMesCheckBox).Name)
            {
                var c = ((LcrMesCheckBox)control);
                c.Enabled = isEdit;
                if (c.EnableAlways)
                    c.Enabled = true;
            }
            else if (control.Controls.Count > 0)
            {
                foreach (Control c in control.Controls)
                {
                    SetControlEnable(c, isEdit);
                }
            }
        }

        /// <summary>
        /// 把控件保存为图片
        /// </summary>
        /// <param name="control">控件</param>
        /// <returns>文件绝对路径</returns>
        public static string SaveControlAsPicture(Control control)
        {
            Bitmap bit = new Bitmap(control.Width, control.Height);//实例化一个和窗体一样大的bitmap
            Graphics g = Graphics.FromImage(bit);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.CopyFromScreen(control.PointToScreen(Point.Empty), Point.Empty, control.Size);

            string path = Settings.GetDataPath();
            string file = path + "\\" + DateTime.Now.ToString("yyyyMMdd_hhmmsss") + ".png";
            bit.Save(file);//默认保存格式为PNG，保存成jpg格式质量不是很好

            if (File.Exists(file))
                System.Diagnostics.Process.Start(file);

            return file;
        }

        /// <summary>
        /// 获取当前使用的IP
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            string name = Dns.GetHostName();
            IPAddress[] ipadrlist = Dns.GetHostAddresses(name);
            foreach (IPAddress ipa in ipadrlist)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork && ipa.ToString().StartsWith("192.168."))
                    return ipa.ToString();
            }

            return string.Empty;
        }

        public static string GetCpuId()
        {
            ManagementClass mc = new ManagementClass("Win32_Processor");
            ManagementObjectCollection moc = mc.GetInstances();
            string strID = string.Empty;
            foreach (ManagementObject mo in moc)
            {
                strID = mo.Properties["ProcessorId"].Value.ToString();
                break;
            }

            return strID;
        }
    }

    public enum FormStatus
    {
        Add,
        Edit,
        Copy,
        Browser
    }
}
